#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试简化版脑状态分类逻辑
"""

import sys
import os

# 添加项目根目录到路径
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)

from service.SimplifiedBrainStateService import SimplifiedBrainStateService
from models.brain_state_models import BrainWaveRatesInput
from datetime import datetime

def debug_classification(delta, theta, alpha, beta, gamma, description):
    """
    调试特定脑波比例的分类过程
    """
    print(f"\n=== 调试 {description} ===")
    print(f"输入波段比例: delta={delta}, theta={theta}, alpha={alpha}, beta={beta}, gamma={gamma}")
    
    # 创建测试数据
    test_data = {
        'delta': [delta] * 10,
        'theta': [theta] * 10,
        'alpha': [alpha] * 10,
        'beta': [beta] * 10,
        'gamma': [gamma] * 10
    }
    
    # 创建输入对象
    input_data = BrainWaveRatesInput(
        session_id="debug_session",
        start_time=datetime.now().isoformat(),
        end_time=datetime.now().isoformat(),
        relative_rates=test_data
    )
    
    # 创建服务实例
    service = SimplifiedBrainStateService()
    
    # 计算平均比率
    avg_ratios = service._calculate_average_ratios(test_data)
    print(f"平均波段比例: {avg_ratios}")
    
    # 获取规则
    rules = service.SLEEP_MONITORING_RULES_5BAND
    
    # 分析每个状态的匹配情况
    print("\n各状态匹配分析:")
    candidates = []
    
    for state, rule in rules.items():
        conditions = rule['conditions']
        confidence = service._calculate_state_confidence(avg_ratios, conditions)
        min_confidence = rule.get('min_confidence', 0.5)
        
        print(f"\n  {state} ({rule['chinese_name']})")
        print(f"    条件: {conditions}")
        print(f"    计算置信度: {confidence:.3f}")
        print(f"    最小置信度: {min_confidence}")
        print(f"    是否满足: {'是' if confidence >= min_confidence else '否'}")
        
        if confidence >= min_confidence:
            candidates.append({
                'state': state,
                'confidence': confidence,
                'priority': rule['priority']
            })
    
    print(f"\n候选状态: {candidates}")
    
    # 排序逻辑
    if candidates:
        candidates.sort(key=lambda x: (x['priority'], -x['confidence']))
        print(f"排序后候选状态: {candidates}")
        best_candidate = candidates[0]
        print(f"最终选择: {best_candidate['state']} (置信度: {best_candidate['confidence']:.3f})")
    else:
        print("没有候选状态，将返回信号异常")
    
    # 实际分类结果
    result = service.classify_brain_state(input_data)
    print(f"\n实际分类结果: {result.state} ({result.details['chinese_name']})")
    print(f"实际置信度: {result.confidence}")

def main():
    print("简化版脑状态分类调试工具")
    print("=" * 50)
    
    # 调试清醒状态
    debug_classification(0.08, 0.12, 0.40, 0.30, 0.10, "清醒状态")
    
    # 调试困倦状态
    debug_classification(0.15, 0.50, 0.20, 0.12, 0.03, "困倦状态")
    
    # 调试浅睡眠状态
    debug_classification(0.35, 0.30, 0.15, 0.12, 0.08, "浅睡眠状态")
    
    # 调试REM睡眠状态
    debug_classification(0.08, 0.45, 0.12, 0.25, 0.10, "REM睡眠状态")

if __name__ == "__main__":
    main()